<template>
    <userDialog
        v-model="visible"
        :dialogTitle="`${roleDialogType}用户`"
        width="880px"
        @open="init"
        @handleCloseDialog="handleCloseDialog(false)"
    >
        <template v-slot:userDiagContent>
            <dialogFormContent title="基本信息">
                <template v-slot:form_info="{ isShowInfoFold }">
                    <div v-show="isShowInfoFold">
                        <el-form
                            :rules="addRoleFromRules"
                            ref="queryFormRef"
                            :model="form"
                            class="user_form_content"
                        >
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item
                                        label="角色名称："
                                        prop="type_name"
                                    >
                                        <el-input
                                            v-model="form.type_name"
                                            placeholder="请输入角色名称"
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item
                                        label="角色描述："
                                        prop="describe"
                                    >
                                        <el-input
                                            v-model="form.describe"
                                            autosize
                                            type="textarea"
                                            placeholder="请输入角色描述"
                                        />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </template>
            </dialogFormContent>
            <dialogFormContent title="权限信息">
                <template v-slot:form_info="{ isShowInfoFold }">
                    <div v-show="isShowInfoFold">
                        <appRolePerssion
                            ref="appRolePerssionRef"
                            class="mt-20px"
                            :checkList="appList"
                        ></appRolePerssion>
                    </div>
                    <div v-show="isShowInfoFold">
                        <menusManagerSlelet
                            ref="menusManagerSleletRef"
                            v-model:menuList="menuList"
                        ></menusManagerSlelet>
                    </div>
                </template>
            </dialogFormContent>
            <div class="btnStyle mt-20px">
                <el-button type="primary" @click="upData()"> 提交 </el-button>
                <el-button type="info" @click="handleCloseDialog()">
                    重置
                </el-button>
            </div>
        </template>
    </userDialog>
</template>

<script setup lang="ts">
import UserAPI from "@/api/system/user";
import MenuAPI from "@/api/system/menu";
import RoleAPI from "@/api/system/role";

import { addRoleFromRules } from "@/views/system/roleManager/index";
const emit = defineEmits(["reFresh"]);
const visible = defineModel("modelValue", {
    type: Boolean,
    required: true,
    default: false,
});

const props = defineProps({
    roleDialogType: {
        required: true,
        default: () => "添加" as any,
    },
    roleId: {
        required: true,
        default: () => "",
    },
});
const queryFormRef = ref();
const appRolePerssionRef = ref();
const menusManagerSleletRef = ref();

const form = ref({
    type_name: "",
    describe: "",
});

// 下拉列表类型
interface elselect {
    label: string;
    value: string;
}
const appList = ref([] as elselect[]);
const menuList = ref([] as any[]);

async function getAllCommonUserInfo() {
    return Promise.all([
        // 获取单位列表

        // 获取app列表
        UserAPI.getAppList().then((data) => {
            appList.value = data.map((item: any) => {
                return {
                    label: item.name,
                    value: item.id,
                };
            });
        }),
        // 获取菜单列表
        MenuAPI.getOptions().then((data) => {
            deepEdit(data);
            menuList.value = data;
        }),
    ]).catch((error) => {
        throw error;
    });
}

//
function deepEdit(data: any, parent = null) {
    data.forEach((item: any) => {
        item.chooseStatus = "noneSelect";
        item.choosed = false;
        item.actived = false;
        item.parent = parent;
        if (item.children) {
            deepEdit(item.children, item);
        }
    });
}

// 初始化表单
async function init() {
    await getAllCommonUserInfo();

    if (props.roleDialogType === "编辑" && props.roleId) {
        await getUserDetail();
    }
}

// 获取编辑人员信息
async function getUserDetail() {
    let id = props.roleId;
    await RoleAPI.getRoleInfo(id)
        .then((data: any) => {
            putRoleDetail(data);
        })
        .catch((err: any) => {
            console.log(err);
        });
}

// 回写详情信息
async function putRoleDetail(data: any) {
    //基本信息
    form.value.describe = data.detail.describe;
    form.value.type_name = data.detail.type_name;

    //小程序权限
    appRolePerssionRef.value.appCheckoutList =
        data.menus.front_operation_ids.map((item: any) => {
            return (item = Number(item));
        });
    // 菜单权限
    setChooseData(menuList.value, data.menus.menu_ids);
}

// 选取
const setChooseData = (data: any, resData: any) => {
    data.forEach((ele: any) => {
        if (resData.includes(String(ele.value))) {
            menusManagerSleletRef.value.menusSelect.menuItemChoose(ele, true);
        }
        if (ele.children) {
            setChooseData(ele.children, resData);
        }
    });
};

// 提交
async function upData() {
    //表单校验
    const queryFormIsValid = await queryFormRef.value.validate(
        (isValid: boolean) => {
            return isValid;
        }
    );
    if (!queryFormIsValid) {
        return;
    }

    // 表单参数
    let formParams = {
        ...form.value,
    };
    // app参数
    let appParams = {
        front_operation_ids: appRolePerssionRef?.value?.appCheckoutList || [],
    };
    let menusManagerParams = {
        menu_ids:
            menusManagerSleletRef.value.choosedList?.map((item: any) => {
                return item.value;
            }) || [],
    };

    let api = RoleAPI.addRole;
    let params: any = {
        ...formParams,
        ...appParams,
        ...menusManagerParams,
    };
    if (props.roleDialogType === "编辑" && props.roleId) {
        api = RoleAPI.editRoleInfo;
        params.id = props.roleId;
    }
    await api(params)
        .then((data: any) => {
            console.log(data);
            visible.value = false;
            emit("reFresh");
            ElMessage.success(`${props.roleDialogType}成功`);
        })
        .catch((err: any) => {
            console.log(err);
        });
}

function handleCloseDialog(visibleValue = true) {
    if (!visibleValue) {
        visible.value = visibleValue;
    }

    queryFormRef.value.resetFields();
    queryFormRef.value.clearValidate();

    appRolePerssionRef.value.appCheckoutList = [];

    menusManagerSleletRef.value.allReset();
}

function btnClick() {}
</script>

<style lang="scss" scoped>
.btnStyle {
    padding: 0 255px;
    @include flexLayout;
    justify-content: space-between;
    .el-button {
        font-size: 16px;
        padding: 20px 40px;
    }
}
.user_form_content {
    :deep(.el-form-item) {
        display: flex;
        label {
            width: 94px;
        }
        .el-input,
        .el-select {
            height: 32px;
            width: 372px;
            .el-select__wrapper {
                height: 32px;
                line-height: 32px;
            }
        }
    }
}
</style>
